using CfgTable;
using IQIGame.Onigao.Framework;
using IQIGame.Onigao.GamePlay;
using System.Collections.Generic;

namespace IQIGame.Onigao.Logic
{
    public class ExecShowSpeechBubble : BaseServiceExecution
    {
        /// <summary>
        /// 显示对话气泡
        /// 参数：1：实体tag（为0表示当前实体，只支持单个），2：气泡groupId
        /// </summary>
        public override void Execute(LevelRegion region, LevelPlayer player)
        {
            var config = _config as ExecParamShowSpeechBubble;
            if (!config.tag.TryGetValue(triggerEntity, out int tagOrMcid))
            {
                LogicLog.LogError("无法获取到tagOrMcid.");
                return;
            }

            int groupId = config.groupID;

            LevelEntity entity = null;
            if (tagOrMcid != -1)
            {
                entity = tagOrMcid == 0 ? triggerEntity : region.GetEntityByTagOrMcid(tagOrMcid);
                if (entity == null)
                {
                    LogicLog.LogError($"根据TagOrMcid[{tagOrMcid}]找不到任何实体。");
                    return;
                }
            }

            CfgLevelEntityBubbleGroup cfgEntityBubbleGroup = TableCenter.levelEntityBubbleGroup.Get(groupId);
            //根据条件筛选要播放的气泡
            List<int> validBubbleCids = new List<int>();
            int lifeTime = 0;
            for (int i = 0; i < cfgEntityBubbleGroup.BubbleList.Count; i++)
            {
                int bubbleCid = cfgEntityBubbleGroup.BubbleList[i];
                CfgLevelEntityBubble cfgEntityBubble = TableCenter.levelEntityBubble.Get(bubbleCid);
                (bool isOK, _) = ConditionLevelLogicUtil.Check(cfgEntityBubble.DisplayCondition, region, player, entity);
                if (isOK)
                {
                    lifeTime += cfgEntityBubble.BubbleLifeTime;
                    validBubbleCids.Add(bubbleCid);
                }
            }
            if (validBubbleCids.Count == 0)
            {
                LogicLog.LogError($"根据BubbleGroupId[{groupId}]找不到任何满足条件的气泡。");
                return;
            }
            bool hasOccupation = false;
            //延迟执行气泡服务
            int bubbleDelay = LgLevelConvertUtil.MillisecToFrame(lifeTime);
            int serviceDelay = bubbleDelay + 1; //服务执行的时间稍微晚一点，保证气泡已经结束，占用已经清除
            if (cfgEntityBubbleGroup.EndService.Count > 0)
            {
                //设置占用，仅有服务需要延迟执行时需要设置占用
                player?.entity.OccupiedBy(EntityOccupationStatus.SpeechBubble, groupId,
                    entity, true);
                entity?.OccupiedBy(EntityOccupationStatus.SpeechBubble, groupId,
                    player?.entity, true);
                hasOccupation = player != null || entity != null;
                //延迟执行服务
                for (int i = 0; i < cfgEntityBubbleGroup.EndService.Count; i++)
                {
                    region.level.delayServiceMgr.AddBackendService(player, entity,
                        cfgEntityBubbleGroup.EndService[i],
                        DelayServiceCondition.Realtime, serviceDelay, cfgEntityBubbleGroup.IsSaveDelayService);
                }
            }
            if (hasOccupation)
            {
                //延迟释放玩家和实体的占用
                var occupationDelayAction = ClassPool.Get<LevelReleaseOccupationDelayAction>();
                occupationDelayAction.Initialize(player, triggerEntity, bubbleDelay, EntityOccupationStatus.SpeechBubble);
                region.level.delayActionMgr.AddDelayAction(occupationDelayAction);
            }

            region.NotifyShowSpeechBubble(player, entity, groupId, validBubbleCids);
        }
    }
}
